package com.u17;

import javax.swing.*;
import java.util.ArrayList;

/**
 * @author u17
 * https://leetcode-cn.com/problems/longest-common-prefix/
 */
public class Solution {




    public String longestCommonPrefix(String[] strs) {

        if(strs.length==0||strs==null) {
            return "";
        }

        int length=strs[0].length();

        int cnt=strs.length;

        for(int i=0; i<length; i++){

            char c=strs[0].charAt(i);

            for(int j=1; j<cnt; j++){

                if(i==strs[j].length()||strs[j].charAt(i)!=c) {

                    return strs[0].substring(0,i);

                }
            }
        }
        return strs[0];
    }


    /**
     * 别人的代码
     * @param strs
     * @return
     */
    public String longestCommonPrefix2(String[] strs) {
        if(strs == null || strs.length == 0){
            return "";
        }
        String res = strs[0];
        int i = 1;
        while (i<strs.length){
            while (strs[i].indexOf(res) != 0) {
                res = res.substring(0, res.length() - 1);
            }
            i += 1;
        }
        return res;
    }


    /**
     * 自己改进后
     * @param strs
     * @return
     */
    public String longestCommonPrefix3(String[] strs) {
        if(strs == null || strs.length == 0){
            return "";
        }

        String str = strs[0];
        int i = 0;
        while (i < strs.length) {
            /**
             * strs[i].indexOf(str)表示strs中是否存在str
             * 如果存在，就返回下标
             * 如果不存在，就返回-1
              */
            while (strs[i].indexOf(str) != 0) {
                str = str.substring(0, str.length() - 1);
            }
            i++;
        }
        return str;
    }



    public static void main(String[] args) {

        String[] strs = new String[]{"dog", "flow", "cat"};

        Solution solution = new Solution();
        String s = solution.longestCommonPrefix3(strs);
        System.out.println(s);
    }

}
